package com.hua.api.core.framework.sms;

import com.hua.api.core.util.StringUtil;

import java.util.LinkedList;

@SuppressWarnings("all")
public class SmsWrapper {


    public static void sendCodeSms2PhoneCode(String phoneNumber,String code){
        if(!StringUtil.isEmpty(phoneNumber)){
            String template="您的验证码%s，%s分钟内有效。";
            String content =StringUtil.format(template, code,"30");
            sendCodeSms2Phone(phoneNumber,content);
        }
    }


    public static void sendSmsOnOrderStatusChange(String phoneNumber,String orderNo,String status){
        // 你的订单【变量】状态有变化，订单状态【变量】，详情请登录系统查看。
        if(!StringUtil.isEmpty(phoneNumber)){
            String template="你的订单%s状态有变化，订单状态%s，详情请登录系统查看。";
            String content =StringUtil.format(template, orderNo,status);
            sendCodeSms2Phone(phoneNumber,content);
        }
    }


    public static void sendOperater(String phoneNumber,String orderNo){
        // 你有新的订单需要处理【变量】，请登录系统查看
        if(!StringUtil.isEmpty(phoneNumber)){
            String template="你有新的订单需要处理%s，请登录系统查看";
            String content =StringUtil.format(template, orderNo);
            sendCodeSms2Phone(phoneNumber,content);
        }
    }

    private static void sendCodeSms2Phone(String phoneNumber,String content){
            sender.scheduleSend(phoneNumber,content);
    }

    private static class AsyncSender implements Runnable{

        public void scheduleSend(final String phone, final String content) {
            synchronized(this) {
                jobList.add(()->{
                    try {
                        SmsSendThread.sendSms(phone,content);
                        //SmsFengHuoSender.sendSms(phone,content);
                        //SmsHelper.sendSmsWithPhoneCode(phone, vcode,"30");

                    } catch (Exception e) {
                        //logcat.debug(e);
                    }
                });

                if (jobThread == null) {
                    jobThread = new Thread(this);
                    jobThread.start();
                }
            }
        }

        private void goNext() {
            synchronized(this) {
                if (jobList.size() > 0) {
                    job = jobList.removeFirst();
                }else{
                    jobThread = null;
                    job = null;
                }
            }
        }

        public void run() {
            for (goNext(); job != null; goNext()) {
                job.run();
            }
        }

        private LinkedList<Runnable> jobList = new LinkedList<Runnable>();
        private Thread jobThread = null;
        private Runnable job = null;
    }

    private static AsyncSender sender = new AsyncSender();

}
